<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Seller\Controllers;


use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\Purchase;
use App\Eloquent\Ygt\ReturnPurchase;
use App\Eloquent\Ygt\ReturnPurchaseMaterial;
use App\Eloquent\Ygt\SellerBill;
use App\Eloquent\Ygt\SellerCompany;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class BillController extends Controller
{
    public $userId        = 25;
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        //$sellerCompanyId    = request('seller_company_id',0);
        //$from==1,厂角色查看某个供应商的账单,$fromId供应商的id
        //$from==2,供应商角色查看其在某个场下的账单,$fromId厂的id
        $from               = request('from',1);
        $fromId             = request('id',0);
        $dealStatus         = request('deal_status',0);//0全部1已处理(结清)
        $page               = request('page',1);
        $limit              = request('limit',10);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $roleType           = $userInfo->role_type;//1工厂角色,2客商,3供应商,4收品单位
        $billWhere          = $moneyWhere = [];
        switch ($from)
        {
            case 1:
                //$from==1,厂角色查看某个供应商的账单,$fromId供应商的id
                if(!$fromId )
                {
                    xThrow( ERR_PARAMETER,'请选择供应商' );
                }
                $companyId          = $userInfo->company_id;
                $sellerCompanyId    = $fromId;
                //取列表的条件
                $billWhere          = [
                    'ygt_seller_bill.company_id'=>$companyId,
                    'ygt_seller_bill.seller_company_id'=>$sellerCompanyId,
                    'ygt_seller_bill.add_user_id'=>$userId,
                ];
                //取金额的条件
                $moneyWhere             = [
                    'company_id'=>$companyId,
                    'seller_company_id'=>$sellerCompanyId,
                    'add_user_id'=>$userId,
                    'type'=>2,
                ];
                break;
            case 2:
                //$from==2,供应商角色查看其在某个场下的账单,$fromId厂的id
                if(!$fromId)
                {
                    xThrow( ERR_PARAMETER,'请选择厂' );
                }
                $companyId          = $fromId;
                $where              = [
                    'company_id'=>$companyId,
                    'user_id'=>$userId,
                ];
                $sellerCompany      = SellerCompany::getInfo($where);
                if(!$sellerCompany)
                {
                    xThrow( ERR_PARAMETER,'请选择厂' );
                }
                $sellerCompanyId    = $sellerCompany->id;
                //取列表的条件
                $billWhere          = [
                    'ygt_seller_bill.company_id'=>$companyId,
                    'ygt_seller_bill.seller_company_id'=>$sellerCompanyId,
                ];
                //取金额的条件
                $moneyWhere         = [
                    'company_id'=>$companyId,
                    'seller_company_id'=>$sellerCompanyId,
                ];
                break;
            default:
                xThrow( ERR_PARAMETER,'不是需要的类型' );
        }
        if($dealStatus == 1)
        {
            $billWhere['ygt_seller_bill.status']    = 1;
        }
//        $lists              = SellerBill::getList($where)->toArray();
        $lists              = SellerBill::getJoinListByType($billWhere)->toArray();
        if($roleType == 3){
            $moneyTxtDefault    = '应收金额';
        }else{
            $moneyTxtDefault    = '应付金额';
        }
        foreach($lists as $key=>$val )
        {
            $statusName         = $val['status'] == 1 ? '已结清' : '未结清';
            $lists[$key]['seller_company_name'] = '供应商名字';
            $lists[$key]['status_name'] = $statusName;
            $lists[$key]['img_path']     = '';
            $moneyTxt           = $val['type'] == 1 ? '付款金额: ' : $moneyTxtDefault;
            $lists[$key]['money']     = $moneyTxt.$val['total_money'];
            $lists[$key]['created_at']     = date('Y-m-d',$val['created_at']);
        }
        $count                  = SellerBill::getCount($billWhere);
        //应付单的金额
        $where                  = $moneyWhere;
        $where['type']          = 2;
        if($dealStatus == 1){
            $where['status']          = 1;
        }
        $moneyType2TotalMoney   = SellerBill::where($where)->sum('total_money');
        //付款单的金额
        $where['type']          = 1;
        if($dealStatus == 1){
            $where['status']          = 1;
        }
        $moneyType1TotalMoney   = SellerBill::where($where)->sum('total_money');
        //付款单的剩余金额
        $where['type']          = 1;
        if($dealStatus == 1){
            $where['status']          = 1;
        }
        $moneyType1NowMoney     = SellerBill::where($where)->sum('now_money');
        $totalMoney             = $moneyType2TotalMoney - ($moneyType1TotalMoney - $moneyType1NowMoney);




        $listData               = [
            'total_money'=>$totalMoney,
            'lists'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $sellerCompanyId    = request('seller_company_id',0);
        $money              = request('money',0);
        if( !$userInfo || !$sellerCompanyId || !$money)
        {
            xThrow( ERR_PARAMETER );
        }
        $money                  = floatval($money);
        $companyId              = $userInfo->company_id;
        $data                   = request()->all();
        //其它信息
        $sn                               = 'ZD'.$_SERVER['REQUEST_TIME'].$userId.mt_rand(1000,9999);
        $data['sn']                       = $sn;
        $data['seller_company_id']      = $sellerCompanyId;
        $data['company_id']              = $companyId;
        $data['total_money']             = $money;
        $data['now_money']               = $money;
        $data['add_user_id']             = $userId;

        $fieldList              = SellerBill::$tableFieldList;
        $tableData              = SellerBill::setDataByTableField($data,$fieldList);
        $tableDataCheckResult   = SellerBill::checkDataByTableField($tableData,$fieldList);
        if($tableDataCheckResult !== true)
        {
            xThrow(ERR_PARAMETER, $tableDataCheckResult);
        }
        $editId                 = SellerBill::editData($tableData,'id');
            if(!$editId)
        {
            xThrow(ERR_UNKNOWN,'添加失败');
        }

//        //发送消息给财务
//        $messageContent = "有新的供应商应付单";
//        $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
//        foreach ($privilegeList as $privilegeId) {
//            $data = [
//                'company_id' => $companyId,
//                'privilege_id' => $privilegeId,
//                'form_user_id' => $userId,
//                'to_user_id' => '',
//                'foreign_key' => $foreignKey,
//                'type' => 29,//下单人生产派单时给财务发消息
//                'type_id' => $orderId,
//                'title' => '采购应付单',
//                'content' => $messageContent,
//                'type_status' => 1,
//            ];
//
//            \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($data);
//        }



        return ['message'=>'添加成功'];
    }
    public function backAdd()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $requestId          = request('id',0);
        if( !$userInfo || !$requestId)
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['id'=>$requestId];
        $info               = ReturnPurchase::where($where)->first();
        if(!$info)
        {
            xThrow( ERR_PARAMETER,'退货信息出错' );
        }
        $purchase           = $info->toArray();
        $purchaseId         = $purchase['id'];
        $companyId          = $purchase['company_id'];
        $sellerCompanyId    = $purchase['supplier_id'];
        $payType            = strval($purchase['payment_method']);
        //取退货单材料信息
        $where              = ['purchase_id'=>$purchaseId];
        $materialList       = ReturnPurchaseMaterial::where($where)->get()->toArray();
        $totalMoney         = 0;
        foreach($materialList as $key=>$val)
        {
            $tempMoney      = $val['num'] * $val['price'];
            $totalMoney     += $tempMoney;
        }
        //生成供应商的第三种账单,----------虽然不知道是干什么用的!!!!!!!!!
        $data = [
            'company_id'=>$companyId,
            'seller_company_id'=>$sellerCompanyId,//厂的供应商id
            'money' => $totalMoney,//金额
            'pay_type' => $payType,//付款方式
            'add_user_id' => $purchase['uid'],//添加人UID，调整为发起人的ID，否则对应的供应商账单将不显示
        ];
        $result = \App\Eloquent\Ygt\SellerBill::insertOneDataByType($data,'id',3);
        if(!$result)
        {
            xThrow(ERR_UNKNOWN,'添加失败');
        }
        return ['message'=>'添加成功'];
    }

}